<div class="layuimini-container layuimini-page-anim">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">触发编号</label>
                            <div class="layui-input-inline">
                                <input type="text" name="id" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">接料源</label>
                            <div class="layui-input-inline">
                                <select id="targetports" name="type" lay-filter="deviceType">
                                    <option value="">请选择接料口</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">送料源</label>
                            <div class="layui-input-inline">
                                <select id="sourceport" name="type" lay-filter="deviceType">
                                    <option value="">请选择送料口</option>
                                </select>
                            </div>
                        </div>

                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加 </button>
                <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="delete"> 删除 </button>
            </div>
        </script>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        </script>

    </div>
</div>

<script>
    layui.use(['form', 'table', 'miniPage', 'element', 'formSelects'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            formSelects = layui.formSelects,
            miniPage = layui.miniPage;
        form.render();

        
        //动态加载 设备列表
        $.ajax({
            type: 'get',
            async: false,
            url: 'api/ports/GetAll',
            dataType: 'json',
            success: function (res) {      
                $.each(res.data, function (index, item) {
                    //通过LayUI.jQuery添加列表项
                    $("#sourceport").append(new Option(item.portName, item.id));
                });
                $.each(res.data, function (index, item) {
                    $("#targetports").append(new Option(item.portName, item.id));
                });

                form.render('select');
            }
        });

        //渲染表格
        table.render({
            elem: '#currentTableId',
            url: 'api/Trigger/GetTriggerByPage',
            parseData: function (res) { //res 即为原始返回的数据
                return {

                    "code": res.code === 200 ? 0 : res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.total, //解析数据长度
                    "data": res.data //解析数据列表
                }
            },
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [[
                { type: "checkbox", width: 50, align: "center" },
                { field: 'id', width: 100, title: 'ID', sort: true, align: "center" },
                { field: 'sourceName', title: '接料口信息', width: 150, align: "center" },
                { field: 'targetNames', title: '送料口信息', sort: true, width: 150, align: "center" },

                { field: 'link', width: 120, title: '连接条件', align: "center" },
                { field: 'assignRobot', width: 150, title: '指定机器人', align: "center" },
                { field: 'priority', width: 100, title: '优先级', align: "center" },
                { title: '操作', minWidth: 120, toolbar: '#currentTableBar', align: "center" }
            ]],
            limits: [10, 15, 20, 25, 50, 100],
            limit: 15,
            page: true,
            id: 'reloadTable',
            even: "true",
            skin: 'row'

        });

        //表格重新加载
        var tablereload = function (search) {
            table.reload('reloadTable',
                {
                    where: {
                        query: search
                    }, page: {
                        curr: 1
                    }
                });
        }

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            var query = {};
            for (var key in data.field) {
                if (data.field[key].length > 0) {
                    query[key] = data.field[key];
                }
            };
            tablereload(JSON.stringify(query));
            return false;
        });

        //启用禁用
        form.on('switch(state)', function (data) {
            var robot = { id: "0", enable: false };
            robot.id = data.elem.attributes['menuId'].nodeValue;
            robot.enable = data.elem.checked;
            var msg = robot.enable ? "启用" : "禁用";
            $.ajax({
                url: '/Trigger/Enable',
                method: 'post',
                contentType: 'application/json',
                cache: false,
                data: JSON.stringify(robot),
                success: function (res) {
                    layer.msg(msg + '成功!', { icon: 1 });
                },
                error: function (data) {
                    layer.msg(msg + '失败!', { icon: 2 });
                }
            });

        });

        //监听 toolbar添加删除
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {   // 监听添加操作
                var content = miniPage.getHrefContent('page/Trigger/AddTrigger.html');
                var openWH = miniPage.getOpenWidthHeight();

                var index = layer.open({
                    title: '添加AGV',
                    type: 1,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: [openWH[0] + 'px', openWH[1] + 'px'],
                    offset: [openWH[2] + 'px', openWH[3] + 'px'],
                    content: content,
                    //关闭弹出框的回调函数，不管弹出框是手动关闭还是通过脚本进行关闭，都执行
                    end: function (index, layero) {
                        tablereload("");
                    }
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
            } else if (obj.event === 'delete') {  // 监听删除操作
                // 监听删除操作
                var checkStatus = table.checkStatus('reloadTable')
                    , data = checkStatus.data;
                layer.close(index);

                var ids = [];
                data.forEach(x => { ids.push(x.id); });
                console.log(JSON.stringify(ids));
                $.ajax({
                    url: '/Trigger/DeleteByIds',
                    method: 'delete',
                    contentType: 'application/json;charset=UTF-8',
                    cache: false,
                    data: JSON.stringify(ids),
                    success: function (res) {
                        if (res.code === 200) {
                            layer.msg('删除成功!', { icon: 1 },
                                function () {
                                    tablereload("");
                                });
                        } else
                            layer.msg('删除失败!', { icon: 2 });
                    },
                    error: function (data) {

                        layer.msg('删除出错!', { icon: 2 });

                    }
                });
            }
        });
 
        //监听操作框事件
        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                var content = miniPage.getHrefContent('page/Trigger/EditTrigger.html');
                var openWH = miniPage.getOpenWidthHeight();

                var index = layer.open({
                    title: '编辑设备',
                    type: 1,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: [openWH[0] + 'px', openWH[1] + 'px'],
                    offset: [openWH[2] + 'px', openWH[3] + 'px'],
                    content: content,
                    success: function (layero, index) {

                        form.val("editTriggerForm",
                            {
                                "id": data.id,
                                "sourceId": data.sourceId,
                                "sourceName": data.sourceName,
                                "targetIds": data.targetIds,
                                "targetNames": data.targetNames,
                                "link": data.link,
                                "priority": data.priority,
                                "assignRobot": data.assignRobot

                            });
                        formSelects.value('select1', data.targetIds.split(','));


                    }
                    //关闭弹出框的回调函数，不管弹出框是手动关闭还是通过脚本进行关闭，都执行
                    , end: function (index, layero) {
                        tablereload("");
                    }
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            } else if (obj.event === 'delete') {
                layer.confirm('您确定要删除吗?', function (index) {
                    var id = obj.data.id;
                    obj.del();
                    $.ajax({
                        method: 'post',
                        contentType: 'application/json;charset=UTF-8',
                        cache: false,
                        url: '/Trigger/Delete/' + JSON.stringify(id),
                        success: function (res) {
                            if (res.code === 200) {
                                console.log(id);

                                layer.msg('删除成功!', { icon: 1 });
                            } else
                                layer.msg('删除失败!', { icon: 2 });
                        },
                        error: function (data) {
                            layer.msg('删除出错!', { icon: 2 });

                        }
                    });
                    layer.close(index);
                });
            }
        });



    });</script>